package cn.ydxiaoshuai.workrecord.truelicense.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * @author 小帅丶
 * @className CommonMethod
 * @Description 通用方法
 * @Date 2021-08-12-19:59
 **/
@Slf4j
public class CommonMethod {
    /**
     * @Author 小帅丶
     * @Description 公共方法提取
     * @Date  2021-08-12 19:55
     * @param shell - 执行的命令
     * @return java.lang.String
     **/
    public static String getSerialNumber(String[] shell) throws Exception {
        //序列号
        String serialNumber = "";
        Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = reader.readLine().trim();
        if(StrUtil.isNotBlank(line)){
            serialNumber = line;
        }
        reader.close();
        return serialNumber;
    }

    /**
     * @Author 小帅丶
     * @Description 公共方法提取
     * @Date  2021-08-12 19:55
     * @param inputStream - 执行命令返回的流
     * @return java.lang.String
     **/
    public static String getSerialNumber(InputStream inputStream) throws Exception {
        //序列号
        String serialNumber = "";
        Scanner scanner = new Scanner(inputStream);
        if(scanner.hasNext()){
            scanner.next();
        }
        if(scanner.hasNext()){
            serialNumber = scanner.next().trim();
        }
        scanner.close();
        return serialNumber;
    }

    public static List<String> getMacByInetAddress() throws Exception{
        List<String> result = new ArrayList<>();
        //1. 获取所有网络接口
        List<InetAddress> inetAddresses = getLocalAllInetAddress();

        if(inetAddresses != null && inetAddresses.size() > 0){
            //2. 获取所有网络接口的Mac地址
            inetAddresses.forEach(inetAddress -> {
                result.add(getMacByInetAddress(inetAddress));
            });
        }
        return result;
    }

    public static List<String> getIpAddress() throws Exception{
        List<String> result = null;
        //获取所有网络接口
        List<InetAddress> inetAddresses = getLocalAllInetAddress();

        if(inetAddresses != null && inetAddresses.size() > 0){
            result = inetAddresses.stream()
                    .map(InetAddress::getHostAddress)
                    .distinct()
                    .map(String::toLowerCase)
                    .collect(Collectors.toList());
        }
        return result;
    }

    /**
     * 获取当前服务器所有符合条件的InetAddress
     * @author zifangsky
     * @date 2018/4/23 17:38
     * @since 1.0.0
     * @return java.util.List<java.net.InetAddress>
     */
    protected static List<InetAddress> getLocalAllInetAddress() throws Exception {
        List<InetAddress> result = new ArrayList<>(4);

        // 遍历所有的网络接口
        for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces.hasMoreElements(); ) {
            NetworkInterface iface = (NetworkInterface) networkInterfaces.nextElement();
            // 在所有的接口下再遍历IP
            for (Enumeration inetAddresses = iface.getInetAddresses(); inetAddresses.hasMoreElements(); ) {
                InetAddress inetAddr = (InetAddress) inetAddresses.nextElement();
                //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
                if(!inetAddr.isLoopbackAddress()
                        && !inetAddr.isLinkLocalAddress()
                        && !inetAddr.isMulticastAddress()){
                    result.add(inetAddr);
                }
            }
        }
        return result;
    }
    /**
     * 获取某个网络接口的Mac地址
     */
    protected static String getMacByInetAddress(InetAddress inetAddr){
        try {
            byte[] mac = NetworkInterface.getByInetAddress(inetAddr).getHardwareAddress();
            StringBuffer stringBuffer = new StringBuffer();
            for(int i=0;i<mac.length;i++){
                if(i != 0) {
                    stringBuffer.append("-");
                }
                //将十六进制byte转化为字符串
                String temp = Integer.toHexString(mac[i] & 0xff);
                if(temp.length() == 1){
                    stringBuffer.append("0" + temp);
                }else{
                    stringBuffer.append(temp);
                }
            }
            return stringBuffer.toString().toUpperCase();
        } catch (SocketException e) {
            log.error("------------------------------- 获取硬件信息MAC地址失败 -------------------------------");
            log.error("错误{}", e);
        }
        return null;
    }

    /**
     * 校验当前服务器的IP/Mac地址是否在可被允许的IP范围内
     * 如果存在IP在可被允许的IP/Mac地址范围内，则返回true
     */
    public static boolean checkIpAddress(List<String> expectedList,List<String> serverList){
        if(expectedList != null && expectedList.size() > 0){
            if(serverList != null && serverList.size() > 0){
                for(String expected : expectedList){
                    if(serverList.contains(expected.trim())){
                        return true;
                    }
                }
            }
            return false;
        }else {
            return true;
        }
    }

    /**
     * 校验当前服务器硬件（主板、CPU等）序列号是否在可允许范围内
     */
    public static boolean checkSerial(String expectedSerial,String serverSerial){
        if(StrUtil.isNotBlank(expectedSerial)){
            if(StrUtil.isNotBlank(serverSerial)){
                if(expectedSerial.equals(serverSerial)){
                    return true;
                }
            }
            return false;
        }else{
            return true;
        }
    }
}
